|
|
|
|
|
|
|
Caution Before opening a random access file for output, implement code to enforce the lengths of columns. That way, if a string value is longer than what the column expects, you can raise an error or event before potentially losing data. Designing a class for this purpose, therefore, is a good, reusable approach. |
|
|
|
|
|
|
|
|
|
Opening Random Access Files |
|
|
|
|
|
|
|
|
Opening a file for random access is pretty easy. The following syntax is required: |
|
|
|
|
|
|
|
|
Open pathname [For Random] As filenumber Len = reclength |
|
|
|
|
|
|
|
|
Although the Random keyword is the default access type for Visual Basic file operations, it is good to explicitly state them. The length (or size) of each row is determined by the reclength value assigned to Len. If the row of information you pass in (as a UDT, for example) is less than reclength, an error occurs. If greater, no error occurs, but your management of disk space will not be optimal. |
|
|
|
|
|
|
|
|
Tip An exception to explicitly naming the type of access in an Open statement is when you create a class called something like RandomFile whose purpose is to facilitate random access file operations. |
|
|
|
|
|
|
|
|
|
Listing 17.1 gives you an example of opening a file for random access. |
|
|
|
|
|
|
|
|
LISTING 17.1 OPENING A FILE FOR RANDOM ACCESS. |
|
|
|
 |
|
|
|
|
1: Dim iFileNumber As Integer
2: Dim lRecLen As Long
3: Dim Teller1Trans As BankTellerTrans
4: 'Specify the length of each row.
5: lRecLen = Len(Teller1Trans)
6: 'Get the next available file number.
7: iFileNum = FreeFile
8: 'Now open the file.
9: Open transactions.txt For Random As iFileNum Len = lRecLen |
|
|
|
|
|